package com.wiscamp.ninechapters.problems.application.handlers;

import com.wiscamp.ninechapters.problems.domain.events.SheetReviewedEvent;
import com.wiscamp.ninechapters.problems.domain.repositories.TaskRepository;
import com.wiscamp.ninechapters.problems.domain.services.TaskService;
import cube.ddd.aspect.HandleServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class SheetReviewedEventHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final TaskRepository taskRepository;

    private final TaskService taskService;

    @Autowired
    public SheetReviewedEventHandler(TaskRepository taskRepository, TaskService taskService) {
        this.taskRepository = taskRepository;
        this.taskService = taskService;
    }

    @Async
    @HandleServiceException
    @EventListener(SheetReviewedEvent.class)
    public void handleEvent(SheetReviewedEvent event) {
        long taskId = event.getTaskId();
        logger.info("答题卡已批改。开始更新任务 {} 状态。", taskId);
        var task = taskRepository.getTask(taskId);
        if (Objects.nonNull(task)) {
            taskService.completeTask(task);
        } else
            logger.error("Cannot find the practice task. The task id is {}.", taskId);
    }
}
